package com.qf.java2105.huangchuang.hotel.factory;

import com.alibaba.druid.util.StringUtils;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 工厂模式
 * @author hcvg
 * @version v1.0
 * @date 2021/09/13
 **/
public class BeanFactory {
    private static final Properties PROPERTIES = new OrderedProperties();

    private static Map<String, Object> map= new HashMap<>();

/*    static {
        try {
            PROPERTIES.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
            Enumeration<?> enumeration = PROPERTIES.propertyNames();
            while (enumeration.hasMoreElements()){
                String beanName = (String) enumeration.nextElement();
                String className = PROPERTIES.getProperty(beanName);
                map.put(beanName, Class.forName(className).newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    static {
        try {
            PROPERTIES.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
            Set<String> beanNames = PROPERTIES.stringPropertyNames();
            for (String beanName : beanNames) {
                String className = PROPERTIES.getProperty(beanName);
                map.put(beanName, Class.forName(className).newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 通用造对象方法
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        return map.get(beanName);
    }
}
